package com.hongyun.tms.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.Date;

/**
 * 日期工具类
 *
 * @author liPeng
 **/
public final class DateUtils {

    private static final java.time.format.DateTimeFormatter DATETIME_FORMATTER = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final java.time.format.DateTimeFormatter DATE_FORMATTER = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static String date2Str(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(date);
    }
    public static String localDateTime2Str(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            return null;
        }
        return localDateTime.format(DATETIME_FORMATTER);
    }
    /**
     * str 2 localDateTime
     *
     * @param str source
     * @return result
     */
    public static LocalDateTime str2LocalDateTime(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        return LocalDateTime.parse(str, DATETIME_FORMATTER);
    }

    public static LocalDate str2LocalDate(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        return LocalDate.parse(str, DATE_FORMATTER);
    }

    /**
     * 获取某个月份第一天
     *
     * @param yearMonthStr 格式2024-05
     * @return localDate
     */
    public static LocalDate getFirstDay(String yearMonthStr) {
        if (StringUtils.isBlank(yearMonthStr)) {
            return null;
        }
        YearMonth yearMonth = YearMonth.parse(yearMonthStr);
        return yearMonth.atDay(1);
    }

    /**
     * 获取某个月份最后一天
     *
     * @param yearMonthStr 格式2024-05
     * @return localDate
     */
    public static LocalDate getLastDay(String yearMonthStr) {
        if (StringUtils.isBlank(yearMonthStr)) {
            return null;
        }
        YearMonth yearMonth = YearMonth.parse(yearMonthStr);
        return yearMonth.atEndOfMonth();
    }

    /**
     * 返回end和begin相差几个小时
     *
     * @param beginTime 开始
     * @param endTime   结束
     * @return hours, 如2.3个小时
     */
    public static BigDecimal calculateDurationInHours(LocalDateTime beginTime, LocalDateTime endTime) {
        if (beginTime == null || endTime == null) {
            throw new IllegalArgumentException("The beginTime and endTime must not be null");
        }

        Duration duration = Duration.between(beginTime, endTime);
        long seconds = duration.getSeconds();

        // Convert seconds to hours as BigDecimal
        BigDecimal hours = BigDecimal.valueOf(seconds).divide(BigDecimal.valueOf(3600), 2, BigDecimal.ROUND_HALF_UP);

        return hours;
    }

}
